<template>
  <div class="pages newServices">
    <div class="pageLevel">
      <div class="from_main1">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="110px">
          <el-form-item label-width='25px' style='margin-bottom: 0px;border-bottom: 1px dashed #ccc;width: 100%'>
            <h3 class="jichu">基础信息</h3>
          </el-form-item>
          <div class="addT">
            <el-row>
              <el-col :span="24">
                <el-form-item label="服务照片" prop="dialogImageUrl" v-if="appRole">
                  <div class="img-list">
                    <div class="img-content" v-for="(item,key) in imagelists" :key="key">
                      <img :src="item">
                      <div class="bottom">
                        <div class="replace"><div>更换图片</div><input type="file" @change="handleChangeImage(item,key,$event)"></div>
                        <div class="delete" @click="handleFileRemove(item,key)">删除图片</div>
                      </div>
                    </div>
                    <div class="img-upload" v-if="buttonImg">
                      <el-upload class="uploader" accept="image/*" ref="upload" list-type="picture-card" :show-file-list="false" :action="uploadFile" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                        <el-button type="primary">点击上传</el-button>
                      </el-upload>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="缩略图" prop="thumbnailImageUrl" v-if="appRole">
                  <div class="img-list">
                    <div class="img-content" v-for="(item,key) in imageThumbList" :key="key">
                      <img :src="item">
                      <div class="bottom">
                        <div class="replace"><div>更换图片</div><input type="file" @change="handleChangeImageThumb(item,key,$event)"></div>
                        <div class="delete" @click="handleFileRemoveThumb(item,key)">删除图片</div>
                      </div>
                    </div>
                    <div class="img-upload" v-if="buttonImgThumb">
                      <el-upload class="uploader" accept="image/*" ref="upload" list-type="picture-card" :show-file-list="false" :action="uploadFile" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFileThumb">
                        <el-button type="primary">点击上传</el-button>
                      </el-upload>
                    </div>
                  </div>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="服务名称" prop="sername">
                  <el-input v-model="ruleForm.sername" size="small" maxlength="30" clearable placeholder="如：宝宝游泳抚触 "></el-input>
                  <span>(4～30字)</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="适合年龄" prop="age2">
                  <div style="display: flex;">
                    <el-select v-model="ruleForm.age1" placeholder="请选择" size="small" style="width:150px;">
                      <el-option v-for="item in options" v-if='item.value >= 0' :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    <div>&nbsp;&nbsp;-&nbsp;&nbsp;</div>
                    <el-select v-model="ruleForm.age2" placeholder="请选择" size="small" style="width:150px;">
                      <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="服务时长" prop="sertime">
                  <el-input v-model="ruleForm.sertime" size="small" clearable placeholder="正整数" minlength="1" maxlength="8" style='width: 200px'>
                    <template slot='append'>分钟</template>
                  </el-input>
                </el-form-item>
                <el-form-item label-width='20px'>
                  <el-checkbox v-model="ruleForm.useTime" :true-label='1' :false-label='0'>不占用技师时间</el-checkbox>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="服务类型" prop="type">
                  <el-input v-model="ruleForm.type" size="small" clearable placeholder="如：宝宝游泳抚触次卡" maxlength="6"></el-input>
                  <span>(1～6字)</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="销售单价" prop="serdan">
                  <el-input v-model="ruleForm.serdan" size="small" clearable placeholder="在此输入单价，保留两位小数">
                    <template slot='append'>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="会员价" prop="sermen">
                  <el-input v-model="ruleForm.sermen" size="small" clearable placeholder="在此输入会员价，保留两位小数">
                    <template slot='append'>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="服务概括" prop="serviceSummary" v-if="appRole || weChatRole">
                  <el-input show-word-limit type="textarea" :rows="4" placeholder="如：适用于2~3岁的宝宝，一大一小亲子旅游体验！" v-model="ruleForm.serviceSummary" style="width: 350px;" maxlength="60"></el-input>
                  <span>（4～60字）</span>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item label="设置销售提成" prop="serticheng" v-if='!(soUrce !=5&&isShop==0)'>
                  <el-radio-group v-model="ruleForm.saleRoyalty">
                    <el-radio label="0">否</el-radio>
                    <el-radio label="1">是</el-radio>
                  </el-radio-group>
                    <div v-show="ruleForm.saleRoyalty === '1'">
                      <el-select v-model="ruleForm.deductType" size="small">
                         <el-option label="比例提成" value="0"></el-option>
                         <el-option label="固定提成" value="1"></el-option>
                      </el-select>
                      <el-input v-model="ruleForm.deductAmount" size="small"></el-input>
                      <span v-if="ruleForm.deductType == 0">%</span>
                       <span v-else>元</span>
                    </div>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item label="设置劳动提成" prop="serticheng" v-if="!(soUrce !=5&&isShop==0)">
                  <el-radio-group v-model="ruleForm.labourRoyalty" >
                    <el-radio label="0">否</el-radio>
                    <el-radio label="1">是</el-radio>
                  </el-radio-group>
                  <template>
                    <div v-show="ruleForm.labourRoyalty === '1'">
                      <el-select v-model="ruleForm.labourDeductType" size="small">
                         <el-option label="比例提成" value="0"></el-option>
                         <el-option label="固定提成" value="1"></el-option>
                      </el-select>
                      <el-input v-model="ruleForm.labourDeductAmount" size="small"></el-input>
                      <span v-if="ruleForm.labourDeductType == 0">%</span>
                       <span v-else>元</span>
                    </div>
                  </template>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="状态" prop="serstatus">
                  <el-radio-group v-model="ruleForm.serstatus">
                    <el-radio label="0">上架</el-radio>
                    <el-radio label="1">下架</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
                 <el-col :span='24'>
              <el-form-item label='是否需要商品' required>
                <el-radio-group v-model="ruleForm.needGoods">
                  <el-radio :label="0">是</el-radio>
                  <el-radio :label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span='13' class='el-col-block' v-if='ruleForm.needGoods == 0 '>
              <el-button size='mini' type='primary' @click='openAddGoods' class='el-button-bot'>添加商品</el-button>
              <el-table :data="ruleForm.goodsList" border style="width: 100%" class='table-service' max-height='250px'>
                <el-table-column label="序号" width="50" type='index' align='center'></el-table-column>
                <el-table-column prop='goodsName' label="商品名称" width='160' align='center'></el-table-column>
                <el-table-column prop="goodsCode" label="商品条码" width="160" align='center'>
                </el-table-column>
                <el-table-column prop="primaryClassify" label="分类" align='center'>
                </el-table-column>
                <el-table-column prop="goodsNum" label="数量" align='center' width='60'>
                </el-table-column>
                <el-table-column label="操作" align='center' width='140'>
                  <template slot-scope='scope'>
                    <el-button size="mini" @click='goodsNumEdit(scope.$index)' type="text">修改数量</el-button>
                    <el-button size="mini" @click="deleLinkItem(scope.$index, 'goods')" type="text">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            </el-row>
          </div>
          <el-row v-if="appRole">
            <el-col :span="24" class='line' >
              <el-form-item label="门店经营类型" v-if='managementType.length > 0'>
                <el-radio-group v-model="ruleForm.managementTypeId" @change='handleSelectedChange'>
                  <el-radio v-for='(item, index) in managementType' :label="item.id" :key='index'>{{item.name}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-form-item label-width='25px'>
              <h3 class="jichu" v-if='isChanKang'>服务详情 - 适用于产康门店业务</h3>
              <h3 class="jichu" v-else>服务详情 - 适用于非产康门店业务</h3>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="24" v-if="!isChanKang && (appRole||weChatRole)">
              <el-form-item label="服务内容" prop="serverTextarea">
                <el-input type="textarea" :rows="4" placeholder="如：测量体温、体重、身高，亲子被动操（0~3个月），婴儿游泳，沐浴洗澡，抚触按摩。" v-model="ruleForm.serverTextarea" style="width: 550px;" maxlength="100"></el-input>
                <span>（4～100字）</span>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="!isChanKang &&(appRole||weChatRole)">
              <el-form-item label="注" prop="notes">
                <el-input type="textarea" :rows="4"
                          placeholder="如：
                1、每位宝宝由一名家长进入游泳室内陪同;
                2、请提前准备好尿片、替换衣物、婴儿用奶、水，以备宝宝游泳后使用;
                3、游大池需自备泳裤，也可到店购买;
                4、宝宝进入大池游泳前请先帮宝宝把好大小便，如在游泳中途便便，需缴纳200元设备清洁消毒费;"
                          v-model="ruleForm.notes" style="width: 550px;" maxlength="100">
                </el-input>
                <span>（4～100字）</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if='isChanKang && appRole'>
            <el-col :span="24">
              <el-form-item label="功效" prop="effect">
                <el-input type="textarea" :rows="2" placeholder="如：祛湿，改善关节疼痛" v-model="ruleForm.effect" style="width: 550px;" maxlength="60"></el-input>
                <span>（4～60字）</span>
              </el-form-item>
            </el-col>
            <el-col :span='24'>
              <el-form-item label="适用人群" prop="forPeople">
                <el-input placeholder="如：女性，产妇，孕妇" v-model="ruleForm.forPeople" size='small' style="width: 550px;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span='24'>
              <el-form-item label="服务部位" prop="position">
                <el-input placeholder="如：背部，腹部" v-model="ruleForm.position" size='small' maxlength='20' style="width: 550px;"></el-input>
                <span>（2～20字）</span>
              </el-form-item>
            </el-col>
            <el-col :span='24'>
              <el-form-item label="添加服务环节" required>
                <el-button size='mini' type='primary' @click='openAddItem()'>添加步骤</el-button>
              </el-form-item>
            </el-col>
            <el-col :span='13' class='el-col-block' v-if='appRole'>
              <el-table :data="ruleForm.linkList" border style="width: 100%" class='table-service' max-height='250px'>
                <el-table-column type="index" label="服务步骤" width="100" align='center'></el-table-column>
                <el-table-column prop="serviceContent" label="服务内容" width="200" align='center'>
                </el-table-column>
                <el-table-column prop="serviceTime" label="时长" align='center' width='120'>
                  <template slot-scope='scope'>
                    <span v-if='scope.row.serviceTime'>{{scope.row.serviceTime}}分钟</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align='center'>
                  <template slot-scope='scope'>
                    <el-button size="mini" @click="moveto(scope.$index, -1)" type="text" :disabled='scope.$index == 0'>上移</el-button>
                    <el-button size="mini" @click="moveto(scope.$index, 1)" type="text" :disabled='scope.$index == ruleForm.linkList.length - 1'>下移</el-button>
                    <el-button size="mini" @click='openAddItem(scope.$index)' type="text">修改</el-button>
                    <el-button size="mini" @click="deleLinkItem(scope.$index, 'service')" type="text">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>

            <el-col>
              <el-form-item label='注' prop='notes' v-if='appRole'>
                <el-input type="textarea" :rows="4" placeholder="要多注意脸部补水，建议第一个星期每天1张面膜。" v-model="ruleForm.notes" style="width: 550px;"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row v-if="!appRole && isChanKang">
            <el-col :span='24'>
              <el-form-item label='是否需要商品' required>
                <el-radio-group v-model="ruleForm.needGoods">
                  <el-radio :label="0">是</el-radio>
                  <el-radio :label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span='13' class='el-col-block' v-if='ruleForm.needGoods == 0'>
              <el-button size='mini' type='primary' @click='openAddGoods' class='el-button-bot'>添加商品</el-button>
              <el-table :data="ruleForm.goodsList" border style="width: 100%" class='table-service' max-height='250px'>
                <el-table-column label="序号" width="50" type='index' align='center'></el-table-column>
                <el-table-column prop='goodsName' label="商品名称" width='160' align='center'></el-table-column>
                <el-table-column prop="goodsCode" label="商品条码" width="160" align='center'>
                </el-table-column>
                <el-table-column prop="primaryClassify" label="分类" align='center'>
                </el-table-column>
                <el-table-column prop="goodsNum" label="数量" align='center' width='60'>
                </el-table-column>
                <el-table-column label="操作" align='center' width='140'>
                  <template slot-scope='scope'>
                    <el-button size="mini" @click='goodsNumEdit(scope.$index)' type="text">修改数量</el-button>
                    <el-button size="mini" @click="deleLinkItem(scope.$index, 'goods')" type="text">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row> -->
          <el-col :span="24" v-if='appRole'>
            <el-form-item label="服务图文详情" id="mrimg" prop="servDetail">
              <div id="editorElem" style="width: 550px;height:378px;"></div>
            </el-form-item>
          </el-col>
          <div style="width:500px;padding-left: 110px;padding-bottom: 100px">
            <el-button type="primary" @click="submitForm('ruleForm')" class="Determine">保 存</el-button>
            <el-button @click="resetForm('ruleForm')">取 消</el-button>
          </div>
        </el-form>
      </div>
    </div>
     <!------------弹框------------------->
    <el-dialog :title="editItemIndex == null ? '添加服务步骤' : '修改服务步骤'" :visible.sync="showAddItem" width='600px' :show-close='false'>
      <el-form :model="linkItem" ref='linkItemModel' label-width="80px" size='small' :rules='ruleLinkItem' key='showAddItem'>
        <el-form-item label="服务内容" prop='serviceContent'>
          <el-input v-model="linkItem.serviceContent" clearable style='width: 380px' maxlength='20'></el-input>
          <span>（2~20字）</span>
        </el-form-item>
        <el-form-item label="服务时长" prop='serviceTime'>
          <el-input v-model="linkItem.serviceTime" clearable style='width: 380px' maxlength='3'
                    @keyup.native='replace(linkItem, "serviceTime")'>
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style='text-align: center;padding-bottom: 20px'>
        <el-button @click="addItemCancle" size='small'>取 消</el-button>
        <el-button type="primary" @click="addLinkItem" size='small'>保 存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改商品数量" :visible.sync="showGoodsEdit" width='400px' :show-close='false'>
      <el-form key='showGoodsEdit' v-if='showGoodsEdit' style='padding-left: 40px' size='small'>
        <p style='margin-bottom: 10px'>商品名称：{{ruleForm.goodsList[editItemIndex].goodsName}}</p>
        <p style='margin-bottom: 10px'>商品条码：{{ruleForm.goodsList[editItemIndex].primaryClassify}}</p>
        <el-form-item label="商品数量">
          <el-input v-model='ruleForm.goodsList[editItemIndex].goodsNum' style='width: 100px'
                    @keyup.native='replace(ruleForm.goodsList[editItemIndex], "goodsNum")'></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style='text-align: center;padding-bottom: 20px'>
        <el-button type="primary" @click="saveGoodsNum" size='small'>保 存</el-button>
      </div>
    </el-dialog>
      <!-- 添加商品弹框------------------------------------->
    <el-dialog title="商品选择" :visible.sync="goodsSelectVisible" width='65%'>
      <add-goods :goodsSelectVisible.sync='goodsSelectVisible' @addGoodsItem='addGoodsItem' :arr.sync='ruleForm.goodsList'></add-goods>
    </el-dialog>
  </div>
</template>
<script>
var htmlTop =
  '<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title></title>' +
  '<style type="text/css">table {border-top: 1px solid #ccc;border-left: 1px solid #ccc;}' +
  'table td,table th {border-bottom: 1px solid #ccc;border-right: 1px solid #ccc;padding: 3px 5px;}' +
  'table th {border-bottom: 2px solid #ccc;text-align: center;}' +
  'body{ margin:0;padding:15px 15px 15px 15px;background-color:#fff;}' +
  'p{font-size:15px;color:#666666;}' +
  'h3{color:#333;font-size:18px;}' +
  'h1{color:#333;font-size:18px;}' +
  'h2{color:#333;font-size:18px;}' +
  'h4{color:#333;font-size:18px;}' +
  'h5{color:#333;font-size:18px;}' +
  'ul li{font-size:15px;color:#333333;margin-left: -15px;line-height: 37px;}' +
  'blockquote {display: block;border-left: 8px solid #d0e5f2;padding: 5px 10px;margin: 10px 0;line-height: 1.4;font-size: 100%;background-color: #f1f1f1;}' +
  'code {display: inline-block;*display: inline;*zoom: 1;background-color: #f1f1f1;border-radius: 3px;padding: 3px 5px;margin: 0 3px}' +
  'pre code {display: block;}ul, ol {margin: 10px 0 10px 20px;}img{width: 100%;}</style></head><body>'
var htmlfooter = '</body></html>'
import E from 'wangeditor'
var editor = new E('#editorElem')

import { mapState } from 'vuex'
import { uploadText, saveOrUpdateService, uploadFile, getFile, getManagementTypeList } from '@/api'
import u from '@/util'
import addGoods from './children/addGoods'
export default {
  name: 'editor',
  computed: mapState(["sub", "power", "merchantId", "linkName" ,"mobile", "isShop", "soUrce"]),
  data() {
    var newReg1 = (rule, value, callback) => {

      if(value == -1) {
        callback()
      }

      if (parseInt(this.ruleForm.age1) > parseInt(value) ) {
        callback(new Error('起始年龄不能大于结束年龄'))
      } else {
        callback()
      }
    }
    var limitSermen = (rule, value, callback) => {
      if(parseInt(value) > parseInt(this.ruleForm.serdan)) {
        callback(new Error('会员价不能大于销售单价'))
      } else {
        callback()
      }
    }
    var limitSerdan = (rule, value, callback) => {
       if(parseInt(value) <  parseInt(this.ruleForm.sermen)) {
        callback(new Error('会员价不能大于销售单价'))
      } else {
        callback()
      }
    }
    var limitEffeteLength = (rule, value, callback) => {
      if(value.length > 60 || value.length < 4 ) {
        callback(new Error('请输入长度在4~60个字之间'))
      } else {
        callback()
      }
    }
    var limitPositionLength = (rule, value, callback) => {
      if(value.length > 20 || value.length < 2) {
        callback(new Error('请输入长度在2~20个字之间'))
      } else {
        callback()
      }
    }
    return {
      visitTips: false,
      managementType: [], //门店经营类型列表
      uploadFile: '',
      isgu: false,
      editorContent: '',
      isbai: true,
      id: '',
      checked: false,
      news: '',
      //多图
      // dialogVisible: false,
      fileList2: [
        {
          name: '',
          url: ''
        }
      ],
      textarea: '',
      index: '',
      row: {},
      tableDataBegin: '',
      radio: '1',
      ruleForm: {
        dialogImageUrl: '',
        thumbnailImageUrl: '',
        sername: '',
        sertime: '',
        type: '',
        serdan: '',
        sermen: '',
        serticheng: '0',
        sermoey: '',
        sermoey1: '',
        serstatus: '0',
        serviceSummary: '', //服务概括
        serverTextarea: '', //服务内容
        age1: '',
        age2: '',
        notes: '', //注
        linkList: [], //服务环节数组
        needGoods: 0, //是否需要商品 (0:是 1:否)
        goodsList: [],//商品集合
        useTime: 0, //是否占用时间
        managementTypeId: '', //经营类型
        forPeople: '', //人群
        position: '',//部位
        effect: '',//功效
        servDetail: '',
        saleRoyalty: '0', // 是否设置提成
        deductType: '1', //提成类型
        deductAmount: '', //提成金额或者百分比
        labourRoyalty: '0', // 是否设置提成
        labourDeductType: '1', //提成类型
        labourDeductAmount: '' //提成金额或者百分比
      },
      chankangDetail: {
        notes: '',
        editorContent: ''
      },
      swimDetail: {
        notes: '',
        editorContent: ''
      },
      create: false,
      rules: {
        sername: [
          { required: true, message: '请输入服务名称', trigger: 'blur' },
          { min: 4, max: 30, message: '长度在 4 到 30 个字符', trigger: 'blur' },
          { validator: u.valida, trigger: 'blur'}
        ],
        sermoey: [
          { validator: u.checkSpace, trigger: 'blur' },
          { validator: u.validatenum, trigger: 'blur' }
        ],
        sermoey1: [
          { validator: u.checkSpace, trigger: 'blur' },
          { validator: u.validatenum1, trigger: 'blur' }
        ],
        sertime: [
          {
            required: true,
            message: '请输入服务时长',
            trigger: 'blur'
          },
          {
            validator: u.valida,
            trigger: 'blur'
          },
          {
            validator: u.numall,
            trigger: 'blur'
          }
        ],
        type: [
          { required: true, message: '请输入服务类型', trigger: 'blur' },
          { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }
        ],
        serviceSummary: [
          { required: true, message: '请输入服务概括', trigger: 'blur' },
          { min: 4, max: 60, message: '长度在 4 到 60 个字符', trigger: 'blur' }
        ], //服务概括
        serverTextarea: [
          { required: true, message: '请输入服务内容', trigger: 'blur' },
          {
            min: 4,
            max: 100,
            message: '长度在 4 到 100 个字符',
            trigger: 'blur'
          }
        ], //服务内容
        age2: [
          { required: true, message: '请选择年龄', trigger: 'change' },
          { validator: newReg1, trigger: 'change' }
        ],
        notes: [
          { required: true, message: '请输入注', trigger: 'blur' },
          {
            min: 4,
            max: 100,
            message: '长度在 4 到 100 个字符',
            trigger: 'blur'
          }
        ], //服务内容
        serdan: [
          {
            required: true,
            message: '请输入销售单价',
            trigger: 'blur'
          },
          {
            validator: u.valida,
            trigger: 'blur'
          },
          {
            validator: u.validateOperatingArea,
            trigger: 'blur'
          },
          {
            validator: u.validatenum1,
            trigger: 'blur'
          },
           {
            validator: limitSerdan, // 会员价不大于销售单价
            trigger: 'blur'
          }
        ],
        sermen: [
          {
            required: true,
            message: '请输入会员价',
            trigger: 'blur'
          },
          {
            validator: u.valida,
            trigger: 'blur'
          },
          {
            validator: u.validateOperatingArea,
            trigger: 'blur'
          },
          {
            validator: u.validatenum1,
            trigger: 'blur'
          },
           {
            validator: limitSermen, // 会员价不大于销售价格
            trigger: 'blur'
          },
        ],
        serticheng: [
          {
            required: false,
            message: '请输入会员价',
            trigger: 'blur'
          }
        ],
        serstatus: [
          {
            required: true,
            message: '请选择状态',
            trigger: 'blur'
          }
        ],
        dialogImageUrl: [{required: true,  message: '请上传服务图片',}],
        thumbnailImageUrl: [{required: true,  message: '请上传缩略图',}],
        forPeople: [{required: true,  message: '请输入适用人群',}],
        position: [{required: true,  message: '请上输入服务部位',},{
          validator: limitPositionLength,
          trigger: 'blur'
        }],
        effect: [{required: true,  message: '请上输入功效',},{
          validator: limitEffeteLength,
          trigger: 'blur'

        }],
        servDetail: [{required: true, message: '请输入图文详情'}],
      },
      pass: null, //是否上传成功
      imagelist: [],
      imagelists: [],
      imageThumbList: [],
      age: [], //年龄
      buttonImg: true,
      buttonImgThumb: true,
      editItemIndex: null, // 新建/编辑服务
      showAddItem: false, //添加服务弹框
      goodsSelectVisible: false, //添加商品弹框
      showGoodsEdit: false, //修改商品
      goodsCurrentNum: null, //商品数量
      isChanKang: false,
      linkItem: {
        serviceContent: '',    //服务内容
        serviceTime: null      //服务时长
      }, //添加服务环节
      ruleLinkItem: {
        serviceContent: [{ required: true, message: '请输入服务内容', trigger: 'blur' },
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
        serviceTime: [{validator: u.validNumInt, trigger: 'blur'}]
      },
      options: [
        { value: '-1', label: '不限制' },
        { value: '0', label: '0岁' },
        { value: '1', label: '1岁' },
        { value: '2', label: '2岁' },
        { value: '3', label: '3岁' },
        { value: '4', label: '4岁' },
        { value: '5', label: '5岁' },
        { value: '6', label: '6岁' },
        { value: '7', label: '7岁' },
        { value: '8', label: '8岁' },
        { value: '9', label: '9岁' },
        { value: '10', label: '10岁' },
        { value: '11', label: '11岁' },
        { value: '12', label: '12岁' },
        { value: '13', label: '13岁' },
        { value: '14', label: '14岁' },
        { value: '15', label: '15岁' },
        { value: '16', label: '16岁' },
        { value: '17', label: '17岁' },
        { value: '18', label: '18岁' },
        { value: '19', label: '19岁' },
        { value: '20', label: '20岁' }
      ],
      appRole: true ,
      weChatRole: true,
    }
  },
  watch: {
    imagelists(oldValue, newValue) {
      if (newValue.length == 6 || oldValue.length == 6) {
        this.buttonImg = false
      } else {
        this.buttonImg = true
      }
      if(newValue.length > 0 || oldValue.length > 0) {
        this.ruleForm.dialogImageUrl = 'hello'
      } else {
        this.ruleForm.dialogImageUrl = ''
      }
    },
    imageThumbList(oldValue, newValue) {
      if (newValue.length === 1 || oldValue.length === 1) {
        this.buttonImgThumb = false
        this.ruleForm.thumbnailImageUrl = 'hello'
      } else {
        this.buttonImgThumb = true
        this.ruleForm.thumbnailImageUrl = ''
      }
    }
  },
  created() {
    this.getManagementType()
    this.appRole =  this.setRole('APP权限')
    this.weChatRole = this.setRole('小程序权限')
  },
  mounted() {
    this.edit()
  },
  methods: {
    setRole(key) {
      return u.selectTitle(this.power, key);
    },
    //保存商品数量
    saveGoodsNum(){
      if (!u.validNumber(this.ruleForm.goodsList[this.editItemIndex].goodsNum)) {
        this.$message.error('请输入整数格式')
        return;
      }
      if(!this.ruleForm.goodsList[this.editItemIndex].goodsNum || this.ruleForm.goodsList[this.editItemIndex].goodsNum == 0) {
        this.$message.error('请输入商品数量且不能为0')
        return;
      }
      this.showGoodsEdit = false
    },
    //选择门店经营类型
    handleSelectedChange(val) {
      if (val == 1) {
        this.isChanKang = true
        this.swimDetail.notes = this.ruleForm.notes
        this.swimDetail.editorContent = this.editorContent
        this.$set(this.ruleForm, 'notes', this.chankangDetail.notes)
        this.editorContent = this.chankangDetail.editorContent
      } else {
        this.isChanKang = false
        this.chankangDetail.notes = this.ruleForm.notes
        this.chankangDetail.editorContent = this.editorContent
        this.$set(this.ruleForm, 'notes', this.swimDetail.notes)
        this.editorContent = this.swimDetail.editorContent
      }
      this.editor.txt.html(this.editorContent)
    },
    //查询门店经营类型
    getManagementType () {
      getManagementTypeList({}).then(res => {
        if(res.code == 200){
          this.managementType = res.data.list
          this.ruleForm.managementTypeId = '0'
        }
      })
    },
    //商品数量修改
    goodsNumEdit(index){
      this.showGoodsEdit = true
      this.editItemIndex = index
    },
    //打开商品添加框
    openAddGoods(){
      if(this.ruleForm.goodsList.length >19){
        this.$message.error('商品上限20')
        return
      }
      this.goodsSelectVisible = true
    },
    //商品添加
    addGoodsItem(arr){
      let that = this
      for(let i=0; i<arr.length; i++){
        this.ruleForm.goodsList.push({
          goodsId: arr[i].id,
          goodsName: arr[i].name,
          goodsCode: arr[i].goodsCode,       //商品编码
          primaryClassify: arr[i].primaryClassify,   //商品分类
          goodsClassify: arr[i].primaryClassifyId, //商品分类id
          goodsNum: 1,         //商品数量
        })
      }
      this.$nextTick(function () {
        that.goodsSelectVisible = false
      })
    },
    //上移或者下移
    moveto(index, type) {
      let arr = JSON.parse(JSON.stringify(this.ruleForm.linkList))
      if(type > 0){
        this.ruleForm.linkList= this.swapItems (arr, index, index+1)
      }else {
        this.ruleForm.linkList = this.swapItems (arr, index, index-1)
      }
    },
    swapItems (arr, index1, index2){
      arr[index1] = arr.splice(index2, 1, arr[index1])[0]
      return arr
    },
    //删除服务环节
    deleLinkItem(index, mark){
      if(mark == 'service'){
        this.ruleForm.linkList.splice(index, 1)
        return;
      }
      if (mark == 'goods') {
        this.ruleForm.goodsList.splice(index, 1)
      }
    },
    //添加服务环节
    addLinkItem() {
      let that = this

      if (!this.linkItem.serviceContent || this.linkItem.serviceContent.length < 2) {
        return;
      }
      if (this.showAddItem) {

        if(this.editItemIndex == null){
          this.ruleForm.linkList.push({
            serviceTime: that.linkItem.serviceTime,
            serviceContent: that.linkItem.serviceContent
          })
        } else {
          this.ruleForm.linkList[this.editItemIndex].serviceTime = this.linkItem.serviceTime
          this.ruleForm.linkList[this.editItemIndex].serviceContent = this.linkItem.serviceContent
        }
        this.addItemCancle ()
      }
    },
    //取消添加服务环节
    addItemCancle () {

      this.showAddItem = false
      this.linkItem.serviceContent = ''
      this.linkItem.serviceTime = null
      this.$refs['linkItemModel'].clearValidate()
    },
    openAddItem(index = null) {

      this.editItemIndex = index
      if(index != null){
        this.linkItem.serviceContent = this.ruleForm.linkList[index].serviceContent
        this.linkItem.serviceTime = this.ruleForm.linkList[index].serviceTime
      } else if(this.ruleForm.linkList.length > 9) {
        this.$message.error('服务环节不能超过10项')
        return;
      }
      this.showAddItem = true;
      // this.linkItem.serviceContent = "";
      // this.linkItem.serviceTime = "";
      // this.$refs['linkItemModel'].clearValidate();

    },

    // 编辑器的文本
    getContent() {
      var htmlBody = this.editorContent
      var htmldat = htmlTop + htmlBody + htmlfooter

      if (this.imagelists.length >= 1 || !this.weChatRole || !this.appRole) {
        if(this.imageThumbList.length === 1 || !this.weChatRole|| !this.appRole) {
          if (htmlBody != '' || !this.weChatRole || !this.appRole ) {
            uploadText({
              projectName: '111',
              text: htmldat
            }).then(res => {
              this.urladvice = res.data.id
              this.age[0] = this.ruleForm.age1
              this.age[1] = this.ruleForm.age2
              let data = {
                remarkUrl: this.urladvice,  //编辑器
                remarkText: htmlBody,  //描述
                companyId: this.merchantId, //公司id
                name: this.ruleForm.sername, //服务名称
                serviceTime: this.ruleForm.sertime, //服务时长
                price: this.ruleForm.serdan, //销售价
                memberPrice: this.ruleForm.sermen,
                deductType: this.ruleForm.serticheng, //提成类型
                state: this.ruleForm.serstatus, //状态
                stress: this.ruleForm.notes.replace(/\n/g, '<br/>'), //注
                serviceIntro: this.ruleForm.serviceSummary, //服务概括
                serviceType: this.ruleForm.type, //服务类型
                fitAge: this.age, //适用年龄
                thumbnailImage: this.imageThumbList[0],  // 缩略图
                useTime: this.ruleForm.useTime, //是否占用时间
                managementTypeId: this.ruleForm.managementTypeId, //经营类型
                needGoods: this.ruleForm.needGoods, //是否需要商品 (0:是 1:否)
                goodsList: this.ruleForm.goodsList,  //商品集合
                saleRoyalty: this.ruleForm.saleRoyalty,
                deductType: this.ruleForm.deductType,
                deductAmount: this.ruleForm.deductAmount,
                labourRoyalty: this.ruleForm.labourRoyalty,
                labourDeductType: this.ruleForm.labourDeductType,
                labourDeductAmount: this.ruleForm.labourDeductAmount,
                serviceDetail: this.ruleForm.serverTextarea, //服务内容
              }
              if(this.imagelists.length>0){
                data.image = JSON.stringify(this.imagelists)
              } else{
                data.image = ''
              }
              if (this.isChanKang) {
                data = Object.assign({}, data, {
                  forPeople: this.ruleForm.forPeople, //人群
                  position: this.ruleForm.position,//部位
                  effect: this.ruleForm.effect,//功效
                  linkList: this.ruleForm.linkList, //服务环节数组

                })
              } else {
                // data = Object.assign({}, data, {
                //   serviceDetail: this.ruleForm.serverTextarea, //服务内容
                // })
              }
              saveOrUpdateService(data).then(res => {
                if(res.code == 200) {
                  this.$message.success(res.msg)
                  history.back()
                } else {
                  this.$message.error(res.msg)
                }
              })
            })
          } else {
            this.$message.error('请输入服务图文详情')
          }
        } else {
          this.$message.error('请先上传一张缩略图')
        }
      } else {
        this.$message.error('最少上传一张服务图片')
      }
    },
    // 编辑器
    edit() {
      this.editor = new E('#editorElem')
      this.editor.customConfig.onchange = html => {
        this.editorContent = html
        if (this.editorContent.toString() == '<p><br></p>') {
          this.editorContent = ''
          this.ruleForm.servDetail = ''
        } else {
          this.ruleForm.servDetail = 'hello'
        }
      }
      this.editor.customConfig.zIndex = 100
      this.editor.customConfig.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        "italic", // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'backColor',  // 背景颜色
        'link', // 插入链接
        'list', // 列表
        'justify', // 对齐方式
        'quote', // 引用
        'emoticon',  // 表情
        'image', // 插入图片
        "table", // 表格
        'video',  // 插入视频
      ]
      this.editor.customConfig.customUploadImg = (files, insert) => {
        var data = new FormData();
        data.append("projectName", files[0].name);
        data.append("file", files[0]);
        uploadFile(data).then(res => {
          if(res.code == 200) {
            let a = `${getFile}?id=${res.data.id}`;
            insert(a)
          }
        })
      }
      this.editor.create()
    },
    // 提交表单
    submitForm(formName) {

      if (this.ruleForm.saleRoyalty == '1' && (!this.ruleForm.deductAmount || this.ruleForm.deductAmount == 0)) {
        this.$message.error('请输入销售提成值且大于0！')
        return
      }
      if (this.ruleForm.labourRoyalty == '1' && (!this.ruleForm.labourDeductAmount || this.ruleForm.labourDeductAmount == 0)) {
        this.$message.error('请输入劳动提成值且大于0！')
        return
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          if(+this.ruleForm.serdan < +this.ruleForm.sermen){
            this.$message.error('会员价格不能大于销售单价')
            return
          }
          if (this.isChanKang) {
            let allTime = 0
            if (this.ruleForm.linkList.length < 1) {
              this.$message.error('清添加服务环节')
              return
            }
            if (this.ruleForm.needGoods == 0 && this.ruleForm.goodsList.length < 1) {
              this.$message.error('清添加商品')
              return
            }

            for (let i = 0; i < this.ruleForm.linkList.length; i++) {
              allTime += (+this.ruleForm.linkList[i].serviceTime)
            }
            this.$nextTick(() => {
              if (allTime > this.ruleForm.sertime) {
                this.$message.error('各个服务流程的时长之和不能大于总的服务时长')
                return
              }
              this.getContent()
            })
          }else {
            this.getContent()
          }
        }else {
          return false
        }
      })
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
      history.back()
    },
    // 图片上传验证规则
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg'
      const isLt2M = file.size / 1024 / 1024 < 1

      if (!isJPG) {
        this.$message.error('上传图片格式错误!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 1MB!')
      }
      return isJPG && isLt2M
    },
    // 上传图片
    uploadSectionFile(param) {
      var fileObj = param.file;
      var data = new FormData();
      data.append("projectName", fileObj.name);
      data.append("file", fileObj);
      uploadFile(data).then(res => {
        let a = `${getFile}?id=${res.data.id}`;
        this.imagelists.push(a)
      })
    },
    uploadSectionFileThumb(param) {
      var fileObj = param.file;
      var data = new FormData();
      data.append("projectName", fileObj.name);
      data.append("file", fileObj);
      uploadFile(data).then(res => {
        let a = `${getFile}?id=${res.data.id}`;
        this.imageThumbList.push(a)
      })
    },
    // 更换图片
    handleChangeImage(a, i, e) {
      var fileObj = e.target.files[0]
      var data = new FormData()
      data.append("projectName", fileObj.name);
      data.append("file", fileObj);
      uploadFile(data).then(res => {
        let a = `${getFile}?id=${res.data.id}`;
        this.$set(this.imagelists, i, a)
      })
    },
    handleChangeImageThumb(a, i, e) {
      var fileObj = e.target.files[0]
      var data = new FormData()
      data.append("projectName", fileObj.name);
      data.append("file", fileObj);
      uploadFile(data).then(res => {
        let a = `${getFile}?id=${res.data.id}`;
        this.$set(this.imageThumbList, i, a)
      })
    },
    // 删除图片
    handleFileRemove(file, i) {
      if (!file) {
        return false
      }
      let that = this
      this.$confirm('是否删除此图片？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          that.imagelists.splice(i, 1)
        })
        .catch(meg => console.log(meg))
    },
    handleFileRemoveThumb(file, i) {
      if (!file) {
        return false
      }
      let that = this
      this.$confirm('是否删除此图片？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          that.imageThumbList.splice(i, 1)
        })
        .catch(meg => console.log(meg))
    },
    //字符串过滤
    replace(obj, key) {
      let that = this
      if(!obj[key]){
        return ;
      }
      let event = event || window.event
      if (event.keyCode == 13) {
        setTimeout(() => {
          that.validItem(obj, key);
        }, 100);
      } else {
        that.validItem(obj, key);
      }
    },
    validItem(obj, key) {
      let res = ''
      switch (key) {
        case 'serviceTime':
        case 'goodsNum':
        case 'visit':
          res = u.replaceNumber(obj[key]);
          break;
      }
      this.$set(obj, key, res);
    },
  },
  components: {
    addGoods
  }
}
</script>
<style scoped>
.from_main1 .el-form-item {
  float: left;
}
.from_main1 .el-input {
  width: 350px;
}
.from_main1 .line{
  border-top: 1px dashed #ccc;
}
.from_main1 .line .el-form-item{
  margin-top: 12px;
  margin-bottom: 10px;
}
.from_main1 .jichu {
  color: #444;
}
.from_main1 span {
  font-size: 13px;
  color: #444;
}
.el-col-block {
  background: #fff;
  margin-left: 110px;
  padding: 15px;
  margin-bottom: 20px;
}
.el-col-block .el-button-bot {
  margin-bottom: 15px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-message-box {
  z-index: 9999;
}
#editorElem {
  z-index: -1;
}
.table-service th,.table-service td{
  padding: 6px 0!important;
}
</style>
<style scoped>
* {
  box-sizing: border-box;
}
.img-list {
  overflow: hidden;
  width: 100%;
}
.img-list .img-content {
  float: left;
  text-align: left;
  position: relative;
  display: inline-block;
  width: 200px;
  height: 240px;
  padding: 5px;
  margin: 5px 20px 20px 0;
  border: 1px solid #d1dbe5;
  border-radius: 4px;
  transition: all 0.3s;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
}
.img-list .img-content img {
  display: block;
  width: 100%;
  height: 190px;
  margin: 0 auto;
  border-radius: 4px;
}
.img-list .img-content .name {
  margin-top: 10px;
}
.img-list .img-content .name > div {
  width: 90%;
  text-overflow: ellipsis;
  overflow: hidden;
  height: 25px;
  line-height: 25px;
}
.img-list .img-content:hover .del,
.img-list .img-content:hover .layer {
  opacity: 1;
}
.img-list .img-content .del,
.img-list .img-content .layer {
  opacity: 0;
  transition: all 0.3s;
}
.img-list .img-content .del {
  position: absolute;
  bottom: 10px;
  right: 10px;
  color: #8492a6;
  cursor: pointer;
  font-size: 1.1em;
}
.img-list .img-content .layer {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  height: 200px;
  color: #fff;
  text-align: center;
  z-index: 5;
  background-color: rgba(0, 0, 0, 0.4);
}
.img-list .img-content .layer i {
  font-size: 1.6em;
  margin-top: 80px;
}
.img-list .img-upload {
  float: left;
  width: 200px;
  height: 240px;
  display: table;
  text-align: center;
}
.img-list .uploader {
  width: 100%;
  display: table-cell;
  vertical-align: middle;
}
.bottom {
  width: 100%;
  margin-top: 10px;
}
.replace {
  float: left;
  width: 50%;
  height: 20px;
  text-align: center;
  line-height: 20px;
  position: relative;
  overflow: hidden;
}
.replace div {
  position: absolute;
  width: 100%;
  height: 20px;
  text-align: center;
  line-height: 20px;
}
.replace input {
  position: absolute;
  opacity: 0;
  width: 100%;
  left: 0;
}
.delete {
  float: left;
  width: 50%;
  height: 20px;
  text-align: center;
  line-height: 20px;
}
</style>
